import requests
import sqlite3
from utils import config, logging

class Client:
    def __init__(self):
        self.api_url = config['settings']['api_url']
        self.db_path = config['settings']['db_path']
        self.db_conn = sqlite3.connect(self.db_path)
        self.cursor = self.db_conn.cursor()

    def get_etf_details(self, etf_code):
        # 模拟从服务器获取 ETF 详细信息
        # 实际应用中应替换为真实的网络请求或数据查询逻辑
        mock_data = {
            "name": "Example ETF",
            "code": etf_code,
            "current_price": "100.50",
            "latest_net_value": "99.80",
            "latest_update_time": "14:30:00",
            "latest_update_date": "2023-10-01"
        }
        return mock_data
    def fetch_data(self, endpoint):
        url = f"{self.api_url}/{endpoint}"
        try:
            response = requests.get(url)
            response.raise_for_status()
            data = response.json()
            logging.info(f"Data fetched from {url}")
            return data
        except requests.RequestException as e:
            logging.error(f"Error fetching data from {url}: {e}")
            return None

    def save_data_to_db(self, data, table_name):
        try:
            columns = ', '.join(data.keys())
            placeholders = ', '.join(['?'] * len(data))
            query = f"INSERT INTO {table_name} ({columns}) VALUES ({placeholders})"
            self.cursor.execute(query, list(data.values()))
            self.db_conn.commit()
            logging.info(f"Data saved to {table_name}")
        except sqlite3.Error as e:
            logging.error(f"Error saving data to {table_name}: {e}")

    def close(self):
        self.db_conn.close()
        logging.info("Database connection closed")

def main():
    client = Client()

    # 示例：获取数据并保存到数据库
    data = client.fetch_data('data')
    if data:
        client.save_data_to_db(data, 'data_table')

    client.close()

if __name__ == "__main__":
    main()
